package com.jy.bo.common.conf.config.service;

import com.fqgj.common.utils.StringUtils;
import com.jy.bo.common.conf.config.db.BizConfigDao;
import com.jy.bo.common.conf.config.db.entity.BizConfigEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Author: Amarendar
 * Date: 2020/8/20 上午10:48
 */
@Component
public class DbConfigBaseService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DbConfigBaseService.class);

    @Autowired
    private BizConfigDao bizConfigDao;

    public String getProperty(String key, String defaultValue) {
        BizConfigEntity entity = bizConfigDao.selectByKey(key);
        return entity == null ? defaultValue : entity.getConfigValue();
    }

    public Integer getIntProperty(String key, Integer defaultValue) {
        try {
            return Integer.valueOf(getProperty(key, String.valueOf(defaultValue)));
        } catch (Exception ex) {
            LOGGER.warn("Conversion failed," + key, ex);
            return defaultValue;
        }
    }

    public Boolean getBooleanProperty(String key, Boolean defaultValue) {
        try {
            return Boolean.valueOf(getProperty(key, defaultValue + ""));
        } catch (Exception ex) {
            LOGGER.warn("Conversion failed," + key, ex);
            return defaultValue;
        }
    }

    public void setValue(String key, String value) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        BizConfigEntity entity = bizConfigDao.selectByKey(key);
        if (entity == null) {
            entity = new BizConfigEntity();
            entity.setConfigKey(key);
            entity.setConfigValue(value);
            bizConfigDao.insert(entity);
        } else {
            entity.setConfigValue(value);
            bizConfigDao.updateByPrimaryKey(entity);
        }
    }


}
